Imports System.Windows.Forms
Imports System.ComponentModel

Public Class SelectTextTemplate
  Private _selectedText As String = String.Empty

  Private _TemplateList As TemplateCollection

  Private _PluginSettings As Settings
  Private _FilterApplied As Boolean '= False

  Public Overloads Function ShowDialog(ByVal parent As Object, ByVal pluginSettings As Settings) As DialogResult
    _PluginSettings = pluginSettings
    Return Me.ShowDialog(parent)
  End Function

  Public Property SelectedText() As String
    Get
      Return _selectedText
    End Get
    Set(ByVal value As String)
      _selectedText = value
    End Set
  End Property

#Region "Form Events"

  Private Sub SelectTextTemplate_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

    My.Settings.SelectDialogLocation = Me.Location
    My.Settings.SelectDialogSize = Me.Size

		If Not Me.TemplateDataGridView.SortedColumn Is Nothing Then
			My.Settings.SelectDialogSortedColumn = Me.TemplateDataGridView.SortedColumn.Name
			My.Settings.SelectDialogSortDirection = Me.TemplateDataGridView.SortOrder
		End If

    My.Settings.FilterTitle = Me.TitleTextBox.Text
    My.Settings.FilterCategory = Me.CategoryComboBox.Text

    My.Settings.Save()

  End Sub

  Private Sub SelectTextTemplate_HelpButtonClicked(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.HelpButtonClicked
    Dim about As AboutBox

		about = New AboutBox

		about.ShowDialog(Me)
    about.Dispose()

		e.Cancel = True

  End Sub

  Private Sub SelectTextTemplate_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    TemplateDataGridView.DataSource = Me.m_OrdersBindingSource

    LoadCategories()

    If My.Settings.SelectDialogLocation.Height > -1 Then
      Me.Location = My.Settings.SelectDialogLocation
    End If

    If My.Settings.SelectDialogSize.Height > -1 Then
      Me.Size = My.Settings.SelectDialogSize
    End If

    Try
      LoadTemplates()

    Catch ex As Exception
      MsgBox("Error loading templates. Error " & ex.Message)
    End Try

		If My.Settings.SelectDialogSortedColumn.Length > 0 Then
			Try
				Select Case My.Settings.SelectDialogSortDirection
					Case SortOrder.Ascending
						Me.TemplateDataGridView.Sort(TemplateDataGridView.Columns(My.Settings.SelectDialogSortedColumn), System.ComponentModel.ListSortDirection.Ascending)
					Case SortOrder.Descending
						Me.TemplateDataGridView.Sort(TemplateDataGridView.Columns(My.Settings.SelectDialogSortedColumn), System.ComponentModel.ListSortDirection.Descending)
				End Select


			Catch ex As Exception

			End Try
		End If

    Me.TitleTextBox.Text = My.Settings.FilterTitle
    Me.CategoryComboBox.Text = My.Settings.FilterCategory

		SelectLastUsedTemplate()


  End Sub

#End Region

#Region "Control Events"

  Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
    OkClose()
  End Sub

  Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
    Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
    Me.Close()
  End Sub

  Private Sub CategoryComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CategoryComboBox.SelectedIndexChanged
    If Me.CategoryComboBox.Text = "[Manage Categories]" Then
      Dim frm As New ManageCategories
      If frm.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
        LoadCategories()
      End If
      frm.Dispose()
      Me.CategoryComboBox.Text = ""
      Me.CategoryComboBox.SelectedIndex = -1
    End If

  End Sub

  Private Sub CategoryComboBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CategoryComboBox.TextChanged
    If Me._FilterApplied Then
      RemoveFilter()
    End If

    If TitleTextBox.Text.Length > 0 Or CategoryComboBox.Text.Length > 0 Then
      ApplyFilter()
    End If

  End Sub

  Private Sub FilterButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FilterButton.Click
    'ApplyFilter()
    RemoveFilter()
  End Sub

  Private Sub TemplateDataGridView_UserDeletingRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowCancelEventArgs) Handles TemplateDataGridView.UserDeletingRow

    DeleteSelected()

  End Sub

  Private Sub TemplateDataGridView_UserDeletedRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles TemplateDataGridView.UserDeletedRow

    LoadTemplates()

  End Sub

  Private Sub TemplateDataGridView_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TemplateDataGridView.KeyUp
    If e.KeyCode = Keys.Insert Then
      AddTemplate()
    End If

  End Sub

  Private Sub TemplateDataGridView_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TemplateDataGridView.MouseDoubleClick
    OkClose()

  End Sub

  Private Sub TitleTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TitleTextBox.TextChanged
    If Me._FilterApplied Then
      RemoveFilter()
    End If

    If TitleTextBox.Text.Length > 0 Or CategoryComboBox.Text.Length > 0 Then
      ApplyFilter()
    End If

  End Sub

#End Region

#Region "Link Label Control Events"

  Private Sub AboutLinkLabel_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles AboutLinkLabel.LinkClicked
    Dim about As AboutBox
    about = New AboutBox
    about.ShowDialog(Me)
    about.Dispose()

  End Sub

  Private Sub AddLinkLabel_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles AddLinkLabel.LinkClicked
    AddTemplate()

  End Sub

  Private Sub DeleteLinkLabel_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles DeleteLinkLabel.LinkClicked
    DeleteSelected()

    LoadTemplates()
  End Sub

  Private Sub EditLinkLabel_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles EditLinkLabel.LinkClicked
    Dim TemplatePath As String = ""

    If Me.TemplateDataGridView.SelectedRows.Count = 0 Then
      Return
    End If

    For Each ritem As DataGridViewRow In Me.TemplateDataGridView.SelectedRows
      TemplatePath = CType(ritem.DataBoundItem, TemplateItem).TemplateFilePath

      If IO.File.Exists(TemplatePath) Then
        Try
          Dim EditTemplate As New AddTemplate
          EditTemplate.ShowDialog(Me, Me._PluginSettings, TemplatePath)
          EditTemplate.Dispose()
          LoadCategories()
        Catch ex As Exception
        End Try

      End If

    Next

    LoadTemplates()

  End Sub

  Private Sub OpenFolderLinkLabel_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles OpenFolderLinkLabel.LinkClicked

    If IO.Directory.Exists(_PluginSettings.TemplatePath) Then
      Try
        Process.Start(_PluginSettings.TemplatePath)
      Catch ex As Exception
        MsgBox("Error opening folder, " & _PluginSettings.TemplatePath & vbCrLf & vbCrLf & "Error: " & ex.Message, , "Error Opening Folder")
      End Try

    Else
      MsgBox("The folder, " & _PluginSettings.TemplatePath & " does not exist. This could be because new paths that are manually typed in will not be created until OK is clicked...", , "Folder Does Not Exist")
    End If

  End Sub


  Private Sub PreviewLinkLabel_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles PreviewLinkLabel.LinkClicked
    Dim frm As InsertPreview
    Dim Insert As Text.StringBuilder

    If Me.TemplateDataGridView.SelectedRows.Count = 0 Then
      Return
    End If

    Insert = New Text.StringBuilder

    For Each ritem As DataGridViewRow In Me.TemplateDataGridView.SelectedRows

      If Insert.Length = 0 Then
        Insert.Append(CType(ritem.DataBoundItem, TemplateItem).Insert)
      Else
        Insert.Append(" ")
        Insert.Append(CType(ritem.DataBoundItem, TemplateItem).Insert)
      End If
    Next

    If Insert.Length = 0 Then
      Return
    End If

    frm = New InsertPreview
    Try
      frm.ShowDialog(Me, Insert.ToString)
    Catch ex As Exception
      MsgBox("Error showing the Preview " & Err.Description)
    End Try

    frm.Dispose()

  End Sub

#End Region

#Region "Private Helpers"

  Private Sub AddTemplate()
    Dim Add As AddTemplate
    Add = New AddTemplate

    If Add.ShowDialog(Me, Me._PluginSettings) = Windows.Forms.DialogResult.OK Then
      LoadTemplates()
      LoadCategories()
    End If

  End Sub

  <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId:="System.String.Format(System.String,System.Object)")> <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId:="System.Windows.Forms.Control.set_Text(System.String)")> _
Private Sub ApplyFilter()

    Dim FilterTitle As String = String.Empty
    Dim FilterCategory As String = String.Empty

    Dim WorkingCategory As String = ""

    If _FilterApplied = False Then

      WorkingCategory = Me.CategoryComboBox.Text

      If Me.TitleTextBox.Text.Length = 0 And WorkingCategory.Length = 0 Then
        Return
      End If

      If Me.TitleTextBox.Text.Length > 0 Then
        FilterTitle = String.Format("Title like '{0}'", Me.TitleTextBox.Text)

        Me.Cursor = Cursors.WaitCursor

        Me.m_OrdersBindingSource.Filter = FilterTitle
        Me.Cursor = Cursors.Default

      End If

      If WorkingCategory.Length > 0 Then
        If WorkingCategory = "None/Blank" Then
          WorkingCategory = ""
        End If

        FilterCategory = String.Format("Category = '{0}'", WorkingCategory)

        'listView.Filter = FilterText
        Me.Cursor = Cursors.WaitCursor
        Me.m_OrdersBindingSource.Filter = FilterCategory
        Me.Cursor = Cursors.Default

      End If

      _FilterApplied = True

    Else
      RemoveFilter()
    End If

  End Sub

  Private Sub DeleteSelected()
    Dim TemplatePath As String = ""

    If Me.TemplateDataGridView.SelectedRows.Count = 0 Then
      Return
    End If

    If MsgBox("Delete the " & Me.TemplateDataGridView.SelectedRows.Count & " selected template(s)?", MsgBoxStyle.YesNo, "Are You Sure?") = MsgBoxResult.No Then
      Return
    End If

    For Each ritem As DataGridViewRow In Me.TemplateDataGridView.SelectedRows
      TemplatePath = CType(ritem.DataBoundItem, TemplateItem).TemplateFilePath

      If IO.File.Exists(TemplatePath) Then
        Try
          IO.File.Delete(TemplatePath)

        Catch ex As Exception
          MsgBox("Error deleting Template, " & TemplatePath & vbCrLf & vbCrLf & "Error: " & ex.Message)
        End Try

      End If

    Next

  End Sub

  Private Sub LoadCategories()
    Me.CategoryComboBox.Items.Clear()

    Me.CategoryComboBox.Items.Add("None/Blank")

    Try
      If My.Settings.Categories.Length > 0 Then
        Dim x() As String = My.Settings.Categories.Split(",")
        Array.Sort(x)
        Me.CategoryComboBox.Items.AddRange(x)
      End If

    Catch ex As Exception

    End Try

    Me.CategoryComboBox.Items.Add("[Manage Categories]")

  End Sub

  Private Sub LoadTemplates()
    'Check the template path, to see if it exists
    'if it does, enum all the *.XML files in it.
    'For each file, load the xml
    'if the top element is wlwtexttemplate, load the rest into a TemplateItem
    'Add each TemplateItem to the Listbox

    _TemplateList = Nothing

    _TemplateList = New TemplateCollection

    If _PluginSettings.TemplatePath.Length = 0 Then
      Return
    End If

    If IO.Directory.Exists(_PluginSettings.TemplatePath) = False Then
      Return
    End If

    Dim t As TemplateItem

    Me.Cursor = Cursors.WaitCursor

    For Each templateXML As String In IO.Directory.GetFiles(_PluginSettings.TemplatePath, "*.xml")

      t = New TemplateItem
      t.Load(templateXML)
      _TemplateList.Add(t)
		Next

    TemplateDataGridView.AutoGenerateColumns = False
    m_OrdersBindingSource.DataSource = _TemplateList

    Me.Cursor = Cursors.Default

  End Sub

  Private Sub OkClose()

    If Me.TemplateDataGridView.SelectedRows.Count > 0 Then
      For Each ritem As DataGridViewRow In Me.TemplateDataGridView.SelectedRows

        If SelectedText.Length = 0 Then
          SelectedText = CType(ritem.DataBoundItem, TemplateItem).Insert
        Else
          SelectedText = SelectedText & " " & CType(ritem.DataBoundItem, TemplateItem).Insert
				End If
				_PluginSettings.LastTemplateUsed = CType(ritem.DataBoundItem, TemplateItem).Title
      Next
    End If

    Me.DialogResult = System.Windows.Forms.DialogResult.OK
    Me.Close()

  End Sub

  <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId:="System.Windows.Forms.Control.set_Text(System.String)")> _
  Private Sub RemoveFilter()
    _FilterApplied = False
    m_OrdersBindingSource.RemoveFilter()

  End Sub

	Private Sub SelectLastUsedTemplate()

		If String.IsNullOrEmpty(_PluginSettings.LastTemplateUsed) = True Then Return

		If TemplateDataGridView.Rows.Count = 0 Then Return

		If TemplateDataGridView.SelectedRows.Count > 0 Then
			For Each ritem As DataGridViewRow In Me.TemplateDataGridView.SelectedRows
				ritem.Selected = False
			Next

		End If

		For Each ritem As DataGridViewRow In Me.TemplateDataGridView.Rows

			If CType(ritem.DataBoundItem, TemplateItem).Title = _PluginSettings.LastTemplateUsed Then
				ritem.Selected = True
				Exit For
			End If
		Next

	End Sub

#End Region

End Class
